/**
 * 公共方法
 * modify by 24-09-18
 */
import { setGlobalData, getGlobalData } from '../global'
import pkg from '@system.package'
import network from '@system.network'
import fun from './fun'
const adSerialStr = '1,4,6' //default

function filterSort(data) {
  try {
    return data.sort((a, b) => {
      return Number(b.ext1) - Number(a.ext1)
    })
  } catch (error) {
    console.error('---addReported--- 207', error)
    return []
  }
}
function filterTimer(pullCount = 0) {
  let adconfig = getGlobalData('adconfig')
  let pullUpConfig = adconfig?.quickAppConfig?.pullUpConfig
  let list =
    pullUpConfig && pullUpConfig.length > 0
      ? pullUpConfig
      : [
          { min: 0, max: 3, interval: 0 },
          { min: 4, max: 'Infinity', interval: 1800 }
        ]
  let findItem = list.find(item => {
    let max = ['Infinity', '∞'].indexOf(item.max) > -1 ? 'Infinity' : item.max
    return pullCount >= item.min && pullCount <= max
  })
  let result = findItem?.interval || 0
  // console.log('pullUpConfig:',pullUpConfig,'result:',result,Number(result))
  return Number(result)
}
function filterPull() {
  if (!getGlobalData('tagUser')) {
    console.log('filterPull：不是标签用户')
    return false
  }
  if (getGlobalData('complaintState')) {
    console.log('filterPull：本次已投诉')
    return false
  }
  // 拉起次数判定
  let adconfig = getGlobalData('adconfig')
  let pullUpCnt = adconfig?.pullUpCnt
  let pullCount = getGlobalData('pullCount') || 0
  if (pullCount >= pullUpCnt) {
    console.log('filterPull：满足拉起次数，不再拉起')
    return false
  } else {
    console.log('pullUpCnt(后台配置的值):', pullUpCnt, 'pullCount(本地记录的值):', pullCount)
  }
  return true
}
function getAdSerial(adSerialVal) {
  let arr = []
  let adconfig = getGlobalData('adconfig')
  let advOrderConfig = adSerialVal ? adSerialVal : adconfig?.advOrderConfig || adSerialStr
  if (advOrderConfig != '') {
    let charArray = advOrderConfig.split(',')
    arr = charArray.map(char => {
      return parseFloat(char)
    })
  } else {
    return null
  }
  let index = getGlobalData('adSerialIndex')
  let indexCurrent = index >= 0 && index < arr.length - 1 ? index + 1 : 0
  // console.log('index',index,'indexCurrent',indexCurrent)
  let adSerial = arr[indexCurrent]
  setGlobalData('adSerialIndex', indexCurrent)
  // console.log('adSerial', adSerial)
  return adSerial
}
function filterAppluck(adSerialVal) {
  const adconfig = getGlobalData('adconfig')
  if (!adconfig) {
    console.error('---addReported--- 201', adconfig)
  }
  const appLuck = adconfig?.appLuck || []
  let advOrderConfig = adSerialVal ? adSerialVal : adconfig?.advOrderConfig || adSerialStr
  // console.log('filterAppluck-advOrderConfig:',advOrderConfig)
  if (!advOrderConfig || advOrderConfig == '') {
    console.error('---addReported--- 202', advOrderConfig)
  }
  if (appLuck.length <= 0) {
    console.error('---addReported--- 203 广告位数据空')
    return {}
  } else {
    let appLuckSort = [...appLuck]
    filterSort(appLuckSort)
    // console.log('filterAppluck-appLuck:',JSON.stringify(appLuck))
    // console.log('filterAppluck-appLuckSort:',JSON.stringify(appLuckSort))
    try {
      advOrderConfig = advOrderConfig.split(',').map(Number)
    } catch (error) {
      console.error('---addReported--- 204', error)
    }
    setGlobalData('advOrderConfig', advOrderConfig)
    const result = {}
    const oneIds = {
      templateAdClose: [103, 114, 116, 122],
      templateAdTabbar: [113, 115, 117, 123],
      templateAdButton: [118, 119, 120, 121],
      templateAdApp: [208, 209, 210]
    }
    // const sevenIds = [129, 130, 131, 132, 133]
    const sevenIds = [7011, 7012, 7013]
    const eightIds = [125, 126, 127, 128, 109]
    const nineIds = {
      nineCloseTop: [139, 140, 141],
      nineButton: [142, 143, 144],
      nineCloseBottom: [145, 146, 147],
      nineVirtualKey: [205, 206, 207]
    }
    const tenIds = [148, 149, 150, 151, 152]
    const agdIds = {
      nativeTop: [1311],
      nativeMiddle: [1312],
      nativeBottom: [1313]
    }
    const elevenIds = {
      templateAdTopLeft: [211],
      templateAdTopMiddle: [212],
      templateAdTopRight: [213],
      templateAdClose: [214],
      templateAdButton: [215],
      templateAdTabbar: [216]
    }
    appLuckSort.forEach(item => {
      let params = {
        n: item.positionName,
        v: item.luckId,
        source: item.luckSource,
        price: item.ext1,
        appId: item.adAppId,
        positionId: item.positionId,
        isHide: item.isHide,
        adIdWeight: item.adIdWeight
      }
      const { positionId } = item
      if (positionId == 110) {
        result.kp = result.kp || []
        result.kp.push(params)
      }
      if (positionId == 105) {
        result.bannerTop = result.bannerTop || []
        result.bannerTop.push(params)
      }
      if (positionId == 106) {
        result.bannerBottom = result.bannerBottom || []
        result.bannerBottom.push(params)
      }
      // 1
      if (positionId == 111 && advOrderConfig.includes(1)) {
        if (item.luckSource == 1 || item.luckSource == 9) {
          if (item.luckSource == 1) {
            // 9还未接入
            result.nativeOneMixin = result.nativeOneMixin || []
            result.nativeOneMixin.push(params)
          }
        } else {
          result.nativeOne = result.nativeOne || []
          result.nativeOne.push(params)
        }
      }
      // 2
      if (positionId == 101 && advOrderConfig.includes(2)) {
        result.cp = result.cp || []
        result.cp.push(params)
      }
      // temp-xiaomi
      // if (positionId == 104 && advOrderConfig.includes(2)) {
      //   result.rvFollow = result.rvFollow || []
      //   result.rvFollow.push(params)
      // }
      // 3
      if (positionId == 102 && advOrderConfig.includes(3)) {
        result.qp = result.qp || []
        result.qp.push(params)
      }
      // 4
      if (positionId == 109 && advOrderConfig.includes(4)) {
        result.nativeFour = result.nativeFour || []
        result.nativeFour.push(params)
      }
      // 5
      if (positionId == 104 && advOrderConfig.includes(5)) {
        result.rv = result.rv || []
        result.rv.push(params)
      }
      // 6
      if (positionId == 112 && advOrderConfig.includes(6)) {
        if (item.luckSource == 1 || item.luckSource == 9) {
          if (item.luckSource == 1) {
            // 9还未接入
            result.nativeSixMixin = result.nativeSixMixin || []
            result.nativeSixMixin.push(params)
          }
        } else {
          result.nativeSix = result.nativeSix || []
          result.nativeSix.push(params)
        }
      }
      // 8
      if (eightIds.includes(positionId) && advOrderConfig.includes(8)) {
        result.eight = result.eight || {}
        if (positionId === 125) {
          result.eight.one = result.eight.one || []
          result.eight.one.push(params)
        }
        if (positionId === 125) {
          result.eight.two = result.eight.two || []
          result.eight.two.push(params)
        }
        // else if (positionId === 126) {
        //   result.eight.three = result.eight.three || []
        //   result.eight.three.push(params)
        // }else if (positionId === 127) {
        //   result.eight.four = result.eight.four || []
        //   result.eight.four.push(params)
        // }else if (positionId === 128) {
        //   result.eight.five = result.eight.five || []
        //   result.eight.five.push(params)
        // }
      }
      // 1
      if (advOrderConfig.some(v => Math.round(v) === 1)) {
        for (const [k, v] of Object.entries(oneIds)) {
          if (v.includes(positionId)) {
            result.one = result.one || {}
            result.one[k] = result.one[k] || {}
            result.one[k][positionId] = result.one[k][positionId] || []
            result.one[k][positionId].push(params)
          }
        }
      }
      // 7
      if (sevenIds.includes(positionId) && advOrderConfig.some(v => Math.round(v) === 7)) {
        result.seven = result.seven || {}
        result.seven[positionId] = result.seven[positionId] || []
        result.seven[positionId].push(params)
      }
      // 9
      if (advOrderConfig.some(v => Math.round(v) === 9)) {
        for (const [k, v] of Object.entries(nineIds)) {
          if (v.includes(positionId)) {
            result.nine = result.nine || {}
            result.nine[k] = result.nine[k] || {}
            result.nine[k][positionId] = result.nine[k][positionId] || []
            result.nine[k][positionId].push(params)
          }
        }
      }
      // // 10
      // if (tenIds.includes(positionId) && advOrderConfig.some(v => Math.round(v) === 10)) {
      //   result.ten = result.ten || {}
      //   result.ten[positionId] = result.ten[positionId] || []
      //   result.ten[positionId].push(params)
      // }
      // 10(hw)
      if (advOrderConfig.some(v => Math.round(v) === 10)) {
        for (const [k, v] of Object.entries(agdIds)) {
          if (v.includes(positionId)) {
            result.ten = result.ten || {}
            result.ten[k] = result.ten[k] || {}
            result.ten[k][positionId] = result.ten[k][positionId] || []
            result.ten[k][positionId].push(params)
          }
        }
      }
      // 11
      if (advOrderConfig.some(v => Math.round(v) === 11)) {
        for (const [k, v] of Object.entries(elevenIds)) {
          if (v.includes(positionId)) {
            result.eleven = result.eleven || {}
            result.eleven[k] = result.eleven[k] || {}
            result.eleven[k][positionId] = result.eleven[k][positionId] || []
            result.eleven[k][positionId].push(params)
          }
        }
      }
    })
    console.log('1-filterAppluck result:', result, '\n2-appLuck:', appLuck, '\n3-advOrderConfig:', advOrderConfig)
    return result
  }
}
function getAnyLoadedItem(list) {
  // for (let i in list) {
  //   let item = list[i]
  //   if (item.loaded) {
  //     return item
  //   }
  // }
  // return false
  const filteredData = list.filter(item => item.loaded === true)
  const result =
    filteredData.length > 0
      ? filteredData.reduce((max, current) => (Number(current.price) > Number(max.price) ? current : max))
      : false
  return result
}
function getBestLoadedItem(list) {
  let bestItem = null
  for (let i in list) {
    let item = list[i]
    let source = item?.adData?.source
    let clickBtnTxt = item?.adData?.clickBtnTxt
    item.isActive = isActiveAdItem(source)
    item.isDownload = isDownloadAdItem(clickBtnTxt)
    if (item.loaded) {
      if (
        !bestItem ||
        item.price > bestItem.price ||
        (item.price === bestItem.price && item.isActive && !bestItem.isActive) ||
        (item.price === bestItem.price &&
          item.isActive === bestItem.isActive &&
          item.isDownload &&
          !bestItem.isDownload)
      ) {
        bestItem = item
      }
    }
    // console.log('getBestLoadedItem:index:', i, ': ', list[i])
  }
  // console.log('getBestLoadedItem: ', bestItem)
  return bestItem
}
function isActiveAdItem(str) {
  const activeJson = getGlobalData('activeJson') || {}
  let result = activeJson[str] || false
  return result
}
function isDownloadAdItem(str) {
  const pattern = /下载|安装/
  return pattern.test(str)
}
function getUnloadedCount(list) {
  const filterList = list.filter(item => {
    return !item.loaded
  })
  return filterList.length
}
function isValidPrice(value) {
  if (value === undefined || value === null) {
    return false
  }
  const num = Number(value)
  return !isNaN(num)
}
// 关键行为时间差
function calculateMinutes(t1, t2) {
  // 将时间戳转换为Date对象
  const date1 = Number(t1)
  const date2 = Number(t2)
  // 计算时间差（毫秒）
  const timeDifference = Math.abs(date1 - date2)
  // 将毫秒转换为分钟
  const minutesDifference = Math.floor(timeDifference / (1000 * 60))
  // console.error(date1,date2,timeDifference,minutesDifference)
  return minutesDifference
}
function isDebugDevice() {
  const idInfo = getGlobalData('idInfo')
  let user = idInfo?.user
  if (user == '36cecec57756f3d27') {
    return true
  }
  return false
}
function pkgHasInstall(pkg_name) {
  return new Promise(resolve => {
    pkg.hasInstalled({
      package: pkg_name,
      success: data => {
        let result = data.result
        resolve(result)
      },
      fail: (data, code) => {
        resolve(false)
      }
    })
  })
}
function checkSim() {
  return new Promise((resolve, reject) => {
    network.getSimOperators({
      success: data => {
        // for (const i in data.operators) {
        //   console.log(`operator: ${data.operators[i].operator},slotIndex:${data.operators[i].slotIndex},isDefaultDataOperator:${data.operators[i].isDefaultDataOperator},`)
        // }
        console.log('检测sim卡状态成功:', JSON.stringify(data))
        resolve({
          status: true,
          content: 'true'
        })
      },
      fail: (data, code) => {
        console.error('检测sim卡状态失败:', data, ' code:', code)
        resolve({
          status: false,
          content: `handling fail, code = ${code}, errorMsg=${data}`
        })
      }
    })
  })
}
function checkPkgList(pkgList) {
  if (pkgList.length == 0) return false
  // console.log(getGlobalData('installed-pkg'))
  if (getGlobalData('installed-pkg') !== undefined) {
    return getGlobalData('installed-pkg')
  }
  /**
   * checkState false:要求不安装；true:要求安装
   */
  let n = 0
  const promises = pkgList.map((item, index) => {
    return new Promise((resolve, reject) => {
      pkg.hasInstalled({
        package: item.pkg,
        success: data => {
          n++
          console.log('检测包名成功:' + item.pkg + '的结果是', data.result, '，期望是', item.checkState, ' n:', n)
          if (data.result !== item.checkState) resolve({ ...item, result: data.result })
          else if (n === pkgList.length) reject(false)
        },
        fail: (data, code) => {
          n++
          console.error('检测包名失败:', data, ' code:', code)
          if (n === pkgList.length) reject(false)
        }
      })
    })
  })
  return Promise.race(promises)
    .then(data => {
      setGlobalData('installed-pkg', data)
      return data
    })
    .catch(error => {
      setGlobalData('installed-pkg', false)
      return false
    })
}
async function checkSimPkg(simState, pkgList) {
  const results = await Promise.all([
    simState == 1 ? checkSim() : Promise.resolve(false),
    pkgList.length > 0 ? checkPkgList(pkgList) : Promise.resolve(false)
  ])
  const [checkSimResult, checkPkgResult] = results
  console.log('----- SIM检测 -----', checkSimResult)
  console.log('----- PKG检测 -----', checkPkgResult)
  return { checkSimResult, checkPkgResult }
}
// 按着顺序取广告位置
function getSequencePlacement(obj) {
  const keys = Object.keys(obj)
  if (keys.length <= 0) {
    console.error('getSequencePlacement is null')
    return
  }
  let currentIndex =
    getGlobalData('sequencePlacementIndex') >= 0 ? parseInt(getGlobalData('sequencePlacementIndex')) : -1
  // console.log('sequencePlacementIndex:',currentIndex)
  let newCurrentIndex = (currentIndex + 1) % keys.length
  // console.log('sequencePlacementIndex newCurrentIndex:',newCurrentIndex,keys[newCurrentIndex])
  setGlobalData('sequencePlacementIndex', newCurrentIndex)
  const objKey = keys[newCurrentIndex]
  return obj[objKey]
}
function getRandomNumber(n) {
  return Math.floor(Math.random() * (n + 1))
}

function getRandomData(obj) {
  if (!obj) return []
  const keys = Object.keys(obj)
  const randomKeyIndex = getRandomNumber(keys.length - 1)
  const randomKey = keys[randomKeyIndex]
  return obj[randomKey]
}
// 从数组中任意获取一个元素
function getRandomElement(arr) {
  if (arr.length === 0) {
    return undefined
  }
  const randomIndex = Math.floor(Math.random() * arr.length)
  // console.log('randomIndex', randomIndex)
  return arr[randomIndex]
}
//连续两值都为1
function checkConsecutiveOnes(obj, index) {
  console.log('errorObj checkConsecutiveOnes', obj)
  const keys = Object.keys(obj)
  const length = keys.length
  const currentIndex = keys.indexOf(String(index))
  console.log('currentIndex', currentIndex)
  if (currentIndex === -1 || (currentIndex === 0 && length < 2)) {
    return false
  }
  const prevKey = currentIndex === 0 && length >= 2 ? keys[length - 1] : keys[currentIndex - 1]
  if (obj[prevKey] === 1 && obj[index] === 1) {
    return true
  }
  return false
}
// 从数组中随机n个不重复的数据
function getRandomItems(arr, count = 1) {
  if (!arr) return []
  const arrNew = Object.values(arr)
  let tempArray = [...arrNew]
  const result = []
  for (let i = 0; i < count; i++) {
    if (tempArray.length === 0) {
      tempArray = [...arrNew]
    }
    const randomIndex = Math.floor(Math.random() * tempArray.length)
    const item = tempArray.splice(randomIndex, 1)[0]
    result.push(item)
  }
  // console.log('RandomItems:最终结果：', JSON.stringify(result))
  return result
}
// 从数组中权重分配n个不重复的数据
function getRandomWeightItems(arr, count = 1) {
  if (!arr) return []
  console.log('RandomWeight:原数据：', JSON.stringify(arr))
  const arrNew = Object.values(arr)
  let tempArray = [...arrNew]
  const weightList = Object.keys(arr).map(keys => {
    let eachArr = arr[keys]
    const firstWeight = eachArr.find(item => item.adIdWeight !== undefined && item.adIdWeight !== '')?.adIdWeight
    return {
      key: keys,
      adIdWeight: firstWeight !== undefined && firstWeight !== '' ? parseFloat(firstWeight) : undefined
    }
  })
  console.log('RandomWeight:weightList数据：', JSON.stringify(weightList))
  const filterWeightList = weightList.filter(item => item.adIdWeight > 0) // 过滤权重为0的元素
  // 如果没有权重大于0 随机取
  if (filterWeightList.length === 0) {
    const pz = weightList.filter(item => item.adIdWeight === 0)
    console.log('RandomWeight:权重大于0 数据为空', ' 权重等于0：', pz)
    if (pz.length === 0) {
      return getRandomItems(arr, count)
    } else return []
  } else {
    const txt = JSON.stringify(filterWeightList)
    console.log('RandomWeight:权重大于0 数据为:', txt)
  }
  let available = [...filterWeightList] //数据备份 防止篡改
  let result = []
  for (let i = 0; i < count; i++) {
    if (available.length === 0) {
      console.log('RandomWeight:数据取完 再次循环')
      available = [...filterWeightList]
    }
    // 权重总和
    let totalWeight = available.reduce((sum, item) => sum + item.adIdWeight, 0)
    let random = Math.random() * totalWeight
    for (let i = 0; i < available.length; i++) {
      const item = available[i]
      random -= item.adIdWeight
      if (random <= 0) {
        result.push(arr[item.key]) // 选中当前元素
        console.log('RandomWeight:当前获得随机项', item)
        available.splice(i, 1) // 从可选数组中移除该元素
        break
      }
    }
  }
  console.log('RandomWeight:最终结果：', JSON.stringify(result))
  return result
}
export default {
  ...fun,
  filterSort,
  filterTimer,
  filterPull,
  getAdSerial,
  filterAppluck,
  getAnyLoadedItem,
  getBestLoadedItem,
  getUnloadedCount,
  isValidPrice,
  calculateMinutes,
  isDebugDevice,
  isDownloadAdItem,
  isActiveAdItem,
  pkgHasInstall,
  checkSim,
  checkPkgList,
  checkSimPkg,
  getSequencePlacement,
  getRandomNumber,
  getRandomData,
  getRandomElement,
  checkConsecutiveOnes,
  getRandomItems,
  getRandomWeightItems
}
